package com.photolibrary.base.load;

import android.content.ContentResolver;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Build;
import android.provider.MediaStore;
import android.text.TextUtils;

import com.photolibrary.bean.BaseMedia;

import java.util.ArrayList;
import java.util.List;


/**
 * 作者： ch
 * 时间： 2018/4/10 0010-上午 9:17
 * 描述：
 * 来源：
 */


public class ImageTask extends AsyncTask<Object, Object, List<BaseMedia>> {
    private static final String CONJUNCTION_SQL = "=? or";
    private static final String SELECTION_IMAGE_MIME_TYPE = MediaStore.Images.Media.MIME_TYPE + CONJUNCTION_SQL + " " + MediaStore.Images.Media.MIME_TYPE + CONJUNCTION_SQL + " " + MediaStore.Images.Media.MIME_TYPE + CONJUNCTION_SQL + " " + MediaStore.Images.Media.MIME_TYPE + "=?";
    private static final String SELECTION_IMAGE_MIME_TYPE_WITHOUT_GIF = MediaStore.Images.Media.MIME_TYPE + CONJUNCTION_SQL + " " + MediaStore.Images.Media.MIME_TYPE + CONJUNCTION_SQL + " " + MediaStore.Images.Media.MIME_TYPE + "=?";
    private static final String SELECTION_ID = MediaStore.Images.Media.BUCKET_ID + "=? and (" + SELECTION_IMAGE_MIME_TYPE + " )";
    private static final String SELECTION_ID_WITHOUT_GIF = MediaStore.Images.Media.BUCKET_ID + "=? and (" + SELECTION_IMAGE_MIME_TYPE_WITHOUT_GIF + " )";

    private static final String IMAGE_JPEG = "image/jpeg";
    private static final String IMAGE_PNG = "image/png";
    private static final String IMAGE_JPG = "image/jpg";
    private static final String IMAGE_GIF = "image/gif";
    private static final String[] SELECTION_ARGS_IMAGE_MIME_TYPE = {IMAGE_JPEG, IMAGE_PNG, IMAGE_JPG, IMAGE_GIF};
    private static final String[] SELECTION_ARGS_IMAGE_MIME_TYPE_WITHOUT_GIF = {IMAGE_JPEG, IMAGE_PNG, IMAGE_JPG};

    private static final String DESC = " desc";

    private PSConfig mPickerConfig;

    private PSManager.IMediaCallBack callBack;
    private ContentResolver resolver;
    private int page;
    private String bucketId;

    public ImageTask(PSManager.IMediaCallBack callBack, ContentResolver cr, int page, String id) {
        this.callBack = callBack;
        this.resolver = cr;
        this.page = page;
        this.bucketId = id;
    }

    @Override
    protected List<BaseMedia> doInBackground(Object[] objects) {
        List<BaseMedia> result = new ArrayList<>();
        String columns[] = getColumns();
        Cursor cursor = null;
        try {
            boolean isDefaultAlbum = TextUtils.isEmpty(bucketId);
            boolean isNeedPaging = mPickerConfig == null || mPickerConfig.isNeedPaging();
            boolean isNeedGif = mPickerConfig != null && mPickerConfig.isNeedGif();
            int totalCount = getTotalCount(resolver, bucketId, columns, isDefaultAlbum, isNeedGif);

            String imageMimeType = isNeedGif ? SELECTION_IMAGE_MIME_TYPE : SELECTION_IMAGE_MIME_TYPE_WITHOUT_GIF;
            String[] args = isNeedGif ? SELECTION_ARGS_IMAGE_MIME_TYPE : SELECTION_ARGS_IMAGE_MIME_TYPE_WITHOUT_GIF;
            String order = isNeedPaging ? MediaStore.Images.Media.DATE_MODIFIED + DESC + " LIMIT "
                    + page * 1000 + " , " + 1000 : MediaStore.Images.Media.DATE_MODIFIED + DESC;
            String selectionId = isNeedGif ? SELECTION_ID : SELECTION_ID_WITHOUT_GIF;
            cursor = query(resolver, bucketId, columns, isDefaultAlbum, isNeedGif, imageMimeType, args, order, selectionId);

            addItem(totalCount, result, cursor);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return result;
    }


    @Override
    protected void onPostExecute(List<BaseMedia> list) {
        if (callBack != null) {
            callBack.postMedia(list, list.size());
        }
    }

    private Cursor query(ContentResolver cr, String bucketId, String[] columns, boolean isDefaultAlbum,
                         boolean isNeedGif, String imageMimeType, String[] args, String order, String selectionId) {
        Cursor resultCursor;
        if (isDefaultAlbum) {
            resultCursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, imageMimeType,
                    args, order);
        } else {
            if (isNeedGif) {
                resultCursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, selectionId,
                        new String[]{bucketId, args[0], args[1], args[2], args[3]}, order);
            } else {
                resultCursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, selectionId,
                        new String[]{bucketId, args[0], args[1], args[2]}, order);
            }
        }
        return resultCursor;
    }

    private void addItem(final int allCount, final List<BaseMedia> result, Cursor cursor) {
        if (cursor != null && cursor.moveToFirst()) {
            do {
                String picPath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));

                String id = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID));
                String size = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.SIZE));
                String mimeType = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.MIME_TYPE));
                int width = 0;
                int height = 0;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    width = cursor.getInt(cursor.getColumnIndex(MediaStore.Images.Media.WIDTH));
                    height = cursor.getInt(cursor.getColumnIndex(MediaStore.Images.Media.HEIGHT));
                }

                BaseMedia media = new BaseMedia(picPath, id, size);
                media.setHeight(height);
                media.setWidth(width);

                if (!result.contains(media)) {
                    result.add(media);
                }
            } while (!cursor.isLast() && cursor.moveToNext());
        } else {
        }
    }

    private String[] getColumns() {
        String[] columns;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            columns = new String[]{MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA, MediaStore.Images.Media.SIZE, MediaStore.Images.Media.MIME_TYPE, MediaStore.Images.Media.WIDTH, MediaStore.Images.Media.HEIGHT};
        } else {
            columns = new String[]{MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA, MediaStore.Images.Media.SIZE, MediaStore.Images.Media.MIME_TYPE};
        }
        return columns;
    }

    private int getTotalCount(ContentResolver cr, String bucketId, String[] columns, boolean isDefaultAlbum, boolean isNeedGif) {
        Cursor allCursor = null;
        int result = 0;
        try {
            if (isDefaultAlbum) {
                allCursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
                        SELECTION_IMAGE_MIME_TYPE, SELECTION_ARGS_IMAGE_MIME_TYPE,
                        MediaStore.Images.Media.DATE_MODIFIED + DESC);
            } else {
                if (isNeedGif) {
                    allCursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, SELECTION_ID,
                            new String[]{bucketId, IMAGE_JPEG, IMAGE_PNG, IMAGE_JPG, IMAGE_GIF}, MediaStore.Images.Media.DATE_MODIFIED + DESC);
                } else {
                    allCursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, SELECTION_ID_WITHOUT_GIF,
                            new String[]{bucketId, IMAGE_JPEG, IMAGE_PNG, IMAGE_JPG}, MediaStore.Images.Media.DATE_MODIFIED + DESC);
                }
            }
            if (allCursor != null) {
                result = allCursor.getCount();
            }
        } finally {
            if (allCursor != null) {
                allCursor.close();
            }
        }
        return result;
    }
}
